<template>
  <div class="add-product-container">
    <el-card title="添加商品" class="form-card">
      <el-form
          ref="productFormRef"
          :model="productForm"
          :rules="rules"
          label-width="100px"
          class="product-form"
      >
        <!-- 商户选择下拉框 -->
        <el-form-item label="商户名" prop="merchantId">
          <el-select
              v-model="productForm.merchantId"
              placeholder="请选择商户"
              clearable
              style="width: 100%"
          >
            <el-option
                v-for="merchant in merchants"
                :key="merchant.id"
                :label="merchant.name"
                :value="merchant.id"
            />
          </el-select>
        </el-form-item>

        <!-- 商品名称 -->
        <el-form-item label="商品名" prop="name">
          <el-input
              v-model="productForm.name"
              placeholder="请输入商品名称"
              maxlength="100"
          />
        </el-form-item>

        <!-- 商品描述 -->
        <el-form-item label="商品描述" prop="description">
          <el-input
              v-model="productForm.description"
              placeholder="请输入商品描述"
              type="textarea"
              maxlength="500"
          />
        </el-form-item>

        <!-- 商品价格 -->
        <el-form-item label="商品价格" prop="price">
          <el-input
              v-model.number="productForm.price"
              placeholder="请输入商品价格"
              type="number"
              min="0"
          />
        </el-form-item>

        <!-- 操作按钮 -->
        <el-form-item class="form-actions">
          <el-button type="primary" @click="submitForm">提交</el-button>
          <el-button @click="resetForm">重置</el-button>
          <el-button @click="handleCancel">取消</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import {ref, reactive, onMounted} from 'vue';
import { ElMessage } from 'element-plus';
import server from "../utils/request.js";
import router from "../router/index.js";

// 表单数据
const productForm = reactive({
  merchantId: '', // 商户ID（用于关联）
  merchantName: '', // 商户名称（展示用）
  name: '',
  description: '',
  price: null
});

// 商户列表数据（实际项目中从API获取）
const merchants = ref([
  { id: 1, name: '商户A' },
  { id: 2, name: '商户B' },
  { id: 3, name: '商户C' }
]);

// 表单验证规则
const rules = {
  merchantId: [
    { required: true, message: '请选择商户', trigger: 'change' }
  ],
  name: [
    { required: true, message: '请输入商品名称', trigger: 'blur' },
    { min: 1, max: 100, message: '商品名称长度在1-100个字符之间', trigger: 'blur' }
  ],
  description: [
    { max: 500, message: '商品描述不能超过500个字符', trigger: 'blur' }
  ],
  price: [
    { required: true, message: '请输入商品价格', trigger: 'blur' },
    { type: 'number', min: 0, message: '商品价格不能为负数', trigger: 'blur' }
  ]
};

// 表单引用
const productFormRef = ref(null);

const loadData = async () =>{
  let {data:data} = await server.get("merchant");
  merchants.value=data.data
}
onMounted(()=>{
  loadData()
})
// 提交表单
const submitForm = () => {
  productFormRef.value.validate(async (valid) => {
    if (valid) {
      // 处理商户名称赋值
      const selectedMerchant = merchants.value.find(
          merchant => merchant.id === productForm.merchantId
      );
      if (selectedMerchant) {
        productForm.merchantName = selectedMerchant.name;
      }

      // 模拟提交（实际项目中替换为API调用）
      let {data:data} =await server.post('goods',productForm)
      console.log('提交商品数据:', productForm);
      if (data.code==200){
        // 提交成功后重置表单
        resetForm();
        ElMessage.success('商品添加成功');
        router.push("goodsList")
      }
    } else {
      ElMessage.error('表单验证失败，请检查输入');
      return false;
    }
  });
};

// 重置表单
const resetForm = () => {
  productFormRef.value.resetFields();
};

// 取消操作
const handleCancel = () => {
  // 实际项目中通常用于返回上一页
  ElMessage.info('已取消操作');
  // 可添加路由跳转逻辑：router.back()
  router.back()
};
</script>

<style scoped>
.add-product-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
}

.form-card {
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.product-form {
  margin-top: 20px;
}

.form-actions {
  display: flex;
  justify-content: center;
  gap: 10px;
  margin-top: 30px;
}
</style>>